<template>
	<van-field
		:name="fieldKey"
		:label="label"
		:model-value="currText"
		:placeholder="`请选择${label}`"
		readonly
		is-link
		input-align="right"
		:rules="required ? [{ required: true, message: `${label}必填` }] : []"
		@click="showPopup"
	/>

	<van-popup v-model:show="showPopupFlag" position="bottom" :style="{ height: '30%' }">
		<van-picker show-toolbar :columns="finalOptionList" @confirm="handleConfirm" @cancel="closePopup" />
	</van-popup>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { getDic } from '../../api'

export default {
	name: 'FormPopupSelect',
	props: {
		label: {
			type: String,
			required: true,
		},
		fieldKey: {
			type: String,
			required: true,
		},
		value: {
			type: [String, Number],
			default: '',
		},
		optionList: {
			type: Array,
			default: () => [],
		},
		dicKey: {
			type: String,
			default: '',
		},
		required: {
			type: Boolean,
			default: false,
		},
		field: {
			type: String,
			default: 'text',
		},
		disabled: {
			type: Boolean,
			default: false,
		},
	},
	emits: ['update:value', 'popupConfirm'],
	setup(props, { emit }) {
		const showPopupFlag = ref(false)
		const dicOptionList = ref([])
		const loading = ref(false)

		// 初始化字典数据
		const initDic = async () => {
			if (!props.dicKey) {
				return
			}

			try {
				loading.value = true
				const data = await getDic(props.dicKey)

				// 将字典数据转换为选项列表格式
				dicOptionList.value = data.map((item) => ({
					text: item.dictLabel,
					value: item.dictValue,
				}))

				console.log(`字典[${props.dicKey}]数据加载成功:`, dicOptionList.value)
			} catch (error) {
				console.error(`加载字典[${props.dicKey}]失败:`, error)
			} finally {
				loading.value = false
			}
		}

		// 获取最终的选项列表（优先使用传入的 optionList，否则使用字典数据）
		const finalOptionList = computed(() => {
			if (props.optionList && props.optionList.length > 0) {
				return props.optionList
			}
			return dicOptionList.value
		})

		// 当前显示文本
		const currText = computed(() => {
			if (!props.value && props.value !== 0) return ''

			const option = finalOptionList.value.find((item) => {
				// 支持多种值匹配方式，并处理类型转换
				return (
					String(item.value) === String(props.value) ||
					String(item.code) === String(props.value) ||
					String(item.id) === String(props.value)
				)
			})

			if (option) {
				return option[props.field] || option.text || option.name || option.label || ''
			}

			return props.value
		})

		// 监听 dicKey 变化，重新加载字典数据
		watch(
			() => props.dicKey,
			(newDicKey) => {
				if (newDicKey) {
					initDic()
				}
			}
		)

		// 监听 value 变化，确保显示文本更新
		watch(
			() => props.value,
			(newValue) => {
				console.log('FormPopupSelect value changed:', newValue, 'currText:', currText.value)
			}
		)

		// 显示弹窗
		const showPopup = () => {
			if (props.disabled) {
				return
			}
			showPopupFlag.value = true
		}

		// 关闭弹窗
		const closePopup = () => {
			showPopupFlag.value = false
		}

		// 确认选择
		const handleConfirm = ({ selectedOptions }) => {
			const selected = selectedOptions[0]
			const value = selected.value || selected.code || selected.id

			// 触发 v-model 更新
			emit('update:value', value)

			// 触发自定义事件
			emit('popupConfirm', {
				[props.fieldKey]: value,
				option: selected,
				text: selected[props.field] || selected.text || selected.name || selected.label,
			})

			closePopup()
		}

		// 组件挂载时初始化字典数据
		onMounted(() => {
			initDic()
		})

		return {
			showPopupFlag,
			finalOptionList,
			currText,
			loading,
			showPopup,
			closePopup,
			handleConfirm,
		}
	},
}
</script>
